<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="filterForm.search"
            placeholder="搜索任务标题、描述"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.status" placeholder="任务状态" clearable style="width: 120px">
            <el-option label="待处理" value="pending"/>
            <el-option label="进行中" value="in_progress"/>
            <el-option label="已完成" value="completed"/>
            <el-option label="已取消" value="cancelled"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.priority" placeholder="优先级" clearable style="width: 120px">
            <el-option label="低" value="low"/>
            <el-option label="中" value="medium"/>
            <el-option label="高" value="high"/>
            <el-option label="紧急" value="urgent"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="filterForm.staff_id" placeholder="指派员工" clearable style="width: 150px">
            <el-option
              v-for="staff in staffList"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleCreate" :icon="Plus">新建任务</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="taskList"
      style="width: 100%"
      v-loading="loading"
      row-key="id"
    >
      <el-table-column prop="title" label="任务标题" width="200" show-overflow-tooltip/>
      <el-table-column prop="description" label="任务描述" show-overflow-tooltip/>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="100">
        <template #default="scope">
          <el-tag :type="getPriorityTagType(scope.row.priority)">
            {{ getPriorityText(scope.row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="staff_name" label="指派员工" width="120"/>
      <el-table-column prop="due_date" label="截止日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.due_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            size="small"
            v-if="scope.row.status === 'pending'"
            @click="handleStart(scope.row)"
          >
            开始
          </el-button>
          <el-button
            link
            type="warning"
            size="small"
            v-if="scope.row.status === 'in_progress'"
            @click="handleComplete(scope.row)"
          >
            完成
          </el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.per_page"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任务表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="taskForm"
        :rules="taskRules"
        ref="taskFormRef"
        label-width="100px"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题"/>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="指派员工" prop="staff_id">
          <el-select v-model="taskForm.staff_id" placeholder="选择员工" style="width: 100%">
            <el-option
              v-for="staff in staffList"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="选择优先级" style="width: 100%">
            <el-option label="低" value="low"/>
            <el-option label="中" value="medium"/>
            <el-option label="高" value="high"/>
            <el-option label="紧急" value="urgent"/>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="due_date">
          <el-date-picker
            v-model="taskForm.due_date"
            type="datetime"
            placeholder="选择截止日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ taskForm.id ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import axios from '@/utils/request'

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const staffList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 搜索表单
const filterForm = reactive({
  search: '',
  status: '',
  priority: '',
  staff_id: ''
})

// 分页
const pagination = reactive({
  page: 1,
  per_page: 20,
  total: 0
})

// 任务表单
const taskForm = reactive({
  id: null,
  title: '',
  description: '',
  staff_id: '',
  priority: 'medium',
  due_date: ''
})

// 表单验证规则
const taskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  staff_id: [
    { required: true, message: '请选择指派员工', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

const taskFormRef = ref()

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      per_page: pagination.per_page,
      ...filterForm
    }
    const response = await axios.get('/tasks', { params })
    if (response.data.success) {
      taskList.value = response.data.data.tasks
      pagination.total = response.data.data.pagination.total
    }
  } catch (error) {
    ElMessage.error('加载任务列表失败')
  } finally {
    loading.value = false
  }
}

// 加载员工列表
const loadStaff = async () => {
  try {
    const response = await axios.get('/staff?per_page=100')
    if (response.data.success) {
      staffList.value = response.data.data.staff
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadTasks()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(filterForm, {
    search: '',
    status: '',
    priority: '',
    staff_id: ''
  })
  pagination.page = 1
  loadTasks()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.per_page = val
  pagination.page = 1
  loadTasks()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadTasks()
}

// 新建任务
const handleCreate = () => {
  dialogTitle.value = '新建任务'
  resetForm()
  dialogVisible.value = true
}

// 编辑任务
const handleEdit = (row) => {
  dialogTitle.value = '编辑任务'
  Object.assign(taskForm, row)
  dialogVisible.value = true
}

// 开始任务
const handleStart = async (row) => {
  try {
    const response = await axios.put(`/tasks/${row.id}`, {
      status: 'in_progress'
    })
    if (response.data.success) {
      ElMessage.success('任务已开始')
      loadTasks()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 完成任务
const handleComplete = async (row) => {
  try {
    const response = await axios.put(`/tasks/${row.id}`, {
      status: 'completed'
    })
    if (response.data.success) {
      ElMessage.success('任务已完成')
      loadTasks()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除任务
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除任务 "${row.title}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/tasks/${row.id}`)
      if (response.data.success) {
        ElMessage.success('删除成功')
        loadTasks()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  taskFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (taskForm.id) {
          response = await axios.put(`/tasks/${taskForm.id}`, taskForm)
        } else {
          response = await axios.post('/tasks', taskForm)
        }
        
        if (response.data.success) {
          ElMessage.success(taskForm.id ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadTasks()
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(taskForm, {
    id: null,
    title: '',
    description: '',
    staff_id: '',
    priority: 'medium',
    due_date: ''
  })
  taskFormRef.value?.clearValidate()
}

// 状态相关
const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusTagType = (status) => {
  const map = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

const getPriorityText = (priority) => {
  const map = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return map[priority] || priority
}

const getPriorityTagType = (priority) => {
  const map = {
    low: 'info',
    medium: '',
    high: 'warning',
    urgent: 'danger'
  }
  return map[priority] || ''
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadTasks()
  loadStaff()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>